#pragma once

#include <iostream>
#include <unordered_map>
#include <cerrno>
#include <cstring>
#include <sys/types.h> /* See NOTES */
#include <sys/wait.h>
#include <signal.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <functional>

#include "Log.hpp"
#include "LockGuard.hpp"
#include "Comm.hpp"
#include "nocopy.hpp"
#include "ThreadPool.hpp"
#include "InetAddr.hpp"

const uint16_t defaultport = 8888;
const int defaultbacklog = 1;
const int defaultsize = 1024;

using task_t = std::function<void(void)>;
using callback_t = std::function<void(int, InetAddr &)>;

class TcpServer;

class ThreadData
{
public:
    ThreadData(int sockfd, TcpServer *tptr, InetAddr addr)
        : _sockfd(sockfd), _addr(addr), _tptr(tptr)
    {
    }
    ~ThreadData()
    {
        lg(Info, "sockfd close success close  file descriptor : %d\n", _sockfd);
        close(_sockfd);
    }

public:
    int _sockfd;
    InetAddr _addr;
    TcpServer *_tptr;
};

class TcpServer : public nocopy
{

public:
    TcpServer(uint16_t port = defaultport)
        : _port(port), _isruning(false)
    {
    }
    void Init()
    {
        // 1. 创建文件细节
        _listensock = socket(AF_INET, SOCK_STREAM, 0);
        if (_listensock < 0)
        {
            lg(Fatal, "create socket errror , errno : %d strerror : %s\n", errno, strerror(errno));
            exit(Socket_Err);
        }

        // 固定写法，解决一些少量的bind失败的问题 -- TODO
        int opt = 1;
        setsockopt(_listensock, SOL_SOCKET, SO_REUSEADDR | SO_REUSEPORT, &opt, sizeof(opt));

        lg(Debug, "create socket success , sockfd : %d\n", _listensock);
        // 2.bind 网络信息
        struct sockaddr_in server;
        server.sin_family = AF_INET;
        server.sin_port = htons(_port);
        server.sin_addr.s_addr = INADDR_ANY;

        if (::bind(_listensock, SOCKADDR_IN_TO_SOCKADDR(&server), sizeof(server)) != 0)
        {
            lg(Fatal, "Bind errror , errno : %d strerror : %s\n", errno, strerror(errno));
            exit(Bind_Err);
        }
        lg(Debug, "Bind success , sockfd : %d\n", _listensock);

        // 3. 设置socket为监听状态，tcp特有的
        if (listen(_listensock, defaultbacklog) != 0)
        {
            lg(Fatal, "listen socket errror , errno : %d strerror : %s\n", errno, strerror(errno));
            exit(Listen_Err);
        }
        RegistrationServices("DefaultService", std::bind(&TcpServer::DefaultService, this,
                                                         std::placeholders::_1, std::placeholders::_2));
        // 启动线程池
        threadpool::ThreadPool<task_t>::GetInstance()->Start();
    }

    void Service(int sockfd, InetAddr &peer)
    {
        char buffer[defaultsize];
        while (true)
        {
            int n = read(sockfd, buffer, sizeof(buffer));
            if (n > 0)
            {
                buffer[n] = 0;
                lg(Info, "received a message : %s  , client : [%s]\n", buffer, peer.ToString().c_str());
                std::string massage = "[" + peer.ToString() + "] :";
                massage += buffer;
                write(sockfd, massage.c_str(), massage.size());
            }
            else if (n == 0)
            {
                lg(Info, "client quit.....\n");
                break;
            }
            else
            {
                lg(Error, "read success , errno : %d ,  strerror : %s\n", errno, strerror(errno));
                break;
            }
        }
    }

    static void *HandlerRequest(void *args)
    {
        // 设置分离状态
        pthread_detach(pthread_self());
        ThreadData *td = static_cast<ThreadData *>(args);
        td->_tptr->Service(td->_sockfd, td->_addr);
        delete td;
        return nullptr;
    }
    
    std::string Read(int sockfd)
    {
        char type[128];
        int n = read(sockfd, type, sizeof(type) - 1);
        if (n > 0)
        {
            type[n] = 0;
        }
        else if (n == 0)
        {
            lg(Debug, "client quit....\n");
        }
        else
        {
            lg(Error, "read success , errno : %d ,  strerror : %s\n", errno, strerror(errno));
        }
        return type;
    }
    // 路由
    void route(int sockfd, InetAddr addr)
    {
        // 运行提示服务
        _funcs["DefaultService"](sockfd, addr);
        std::string service = Read(sockfd);
        lg(Debug, "client : %s , selete service : %s \n", addr.ToString().c_str(), service.c_str());
        if (service == "ping")
        {
            _funcs[service](sockfd, addr);
        }
        // translate 翻译service
        else if (service == "translate")
        {
            _funcs[service](sockfd, addr);
        }
        else if (service == "conversion")
        {
            _funcs[service](sockfd, addr);
        }
        
    }

    void DefaultService(int sockfd, InetAddr &addr)
    {
        std::string servicelist;
        for (auto kv : _funcs)
        {
            servicelist += kv.first;
            servicelist += "-|-";
        }

        write(sockfd, servicelist.c_str(), servicelist.size());
    }
    void Start()
    {
        _isruning = true;
        // 对子进程发来的SIGPIPE忽略，避免僵尸进程
        signal(SIGPIPE, SIG_IGN);
        while (_isruning)
        {
            // 获取新链接fd
            struct sockaddr_in peer;
            socklen_t len = sizeof(peer);
            int sockfd = accept(_listensock, SOCKADDR_IN_TO_SOCKADDR(&peer), &len);
            if (sockfd < 0)
            {
                lg(Error, "accept error, errno : %d  ,strerror : %s\n", errno, strerror(errno));
                continue;
            }
            lg(Debug, "accept success , get n new sockfd : %d", sockfd);

            // 在这里提供服务 （多种）
            // v1
            // Service(sockfd);
            // close(sockfd);
            // lg(Info,"file descriptor close , close : %d",sockfd);

            // v2 多进程
            // pid_t pid = fork();
            // if (pid < 0)
            // {
            //     close(sockfd);
            //     continue;
            // }
            // else if (pid == 0)
            // {
            //     close(_listensock);
            //     if (fork() > 0)
            //         exit(0);

            //     // 孙子进程，孤儿进程，被系统领养，正常处理
            //     Service(sockfd);
            //     close(sockfd);
            //     exit(0);
            // }
            // else
            // {
            //     close(sockfd);
            //     pid_t rid = waitpid(pid, nullptr, 0);  //在这里不需要阻塞等待，因为会立马返回
            //     if (rid == pid)
            //     {

            //     }
            // }

            // v3 多进程 信号版
            // pid_t pid = fork();
            // if (pid < 0)
            // {
            //     close(sockfd);
            //     continue;
            // }
            // else if (pid == 0)
            // {
            //     close(_listensock);
            //     Service(sockfd);
            //     close(sockfd);
            //     exit(0);
            // }
            // else
            // {
            //     close(sockfd);
            //     lg(Info, "file descriptor close , close : %d", sockfd);
            //     // 此处不进行等待，在信号层面处理
            // }

            // v4  多线程
            // pthread_t tid;
            // ThreadData *td = new ThreadData(sockfd, this, peer);
            // pthread_create(&tid, nullptr, HandlerRequest, (void *)td);
            // v5 线程池
            task_t t = std::bind(&TcpServer::route, this, sockfd, peer);
            threadpool::ThreadPool<task_t>::GetInstance()->Push(t);
        }
    }

    // 注册服务
    void RegistrationServices(std::string command, callback_t func)
    {
        _funcs[command] = func;
    }

private:
    uint16_t _port;
    int _listensock;
    bool _isruning;
    std::unordered_map<std::string, callback_t> _funcs;
};
